package com.sfac.springboot.config.shiro;

import com.sfac.springboot.modules.account.entity.Resource;
import com.sfac.springboot.modules.account.entity.Role;
import com.sfac.springboot.modules.account.entity.User;
import com.sfac.springboot.modules.account.service.ResourceService;
import com.sfac.springboot.modules.account.service.RoleService;
import com.sfac.springboot.modules.account.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * @author jzq
 * @date 2022/8/31 9:40
 */
@SuppressWarnings({"all"})
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    ResourceService resourceService;

    /**
     * 资源授权
     * 将当前用户对应的角色信息，以及角色所拥有的资源信息放入验证器
     * 通过前端页面 shiro 标签、控制器方法 shiro 注解与验证器比对，实现用户资源授权功能
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorization = new SimpleAuthorizationInfo();
        //从认证中获取当前信息
        User user = (User) principals.getPrimaryPrincipal();

        //获取当前用户的角色列表,并装载到资源授权器中
        List<Role> roles = roleService.getRolesByUserId(user.getId());
        roles.stream().forEach(item->{
            authorization.addRole(item.getRoleName());
            //获取每个角色的资源列表,并装载到资源授权器中
            List<Resource> resources = resourceService.getResourcesByRoleId(item.getId());
            resources.stream().forEach(it->{
                authorization.addStringPermission(it.getPermission());
            });
        });
        return authorization;
    }


    /**
     * 身份认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名
        String userName = (String) token.getPrincipal();
        //通过用户名查找用户信息
        User user = userService.getUserByUserName(userName);
        if (user == null) {
            throw new UnknownAccountException("User name is not exist!");
        }

        /**
         * 封装身份认证器
         * principal: 当前用户信息，可以是user对象，也可以是用户名
         * credentials: 当前用户凭证
         * realmName: 当前 realm 对象的唯一名字
         */
        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
    }

}
